<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/mes/mes/ProductPickMaterial.jsx或ProductPickMaterial.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="grid">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields" :searchFormOptions="searchFormOptions"
            :table="table" :extend="extend" :onInit="onInit" :onInited="onInited" :searchBefore="searchBefore"
            :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore" :rowClick="rowClick"
            :delBefore="delBefore" :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>
            <template #gridFooter>
                <div class="productPickMaterialDetail">
                    <productPickMaterialDetail ref="productPickMaterialDetailRef"></productPickMaterialDetail>
                </div>
            </template>
        </view-grid>
    </div>

    <!-- 明细表选择物料 -->
    <select-material ref="materialRef" @onSelect="onSelectMaterial"></select-material>
    <!-- 选择生产任务(选择数据) -->
    <select-productTask ref="productTaskRef" @onSelectProductTask="onSelectProductTask"></select-productTask>
    <!-- 选择产品(选择数据) -->
    <select-product ref="productRef" @onSelectProduct="onSelectProduct"></select-product>
</template>
<script setup lang="jsx">
import extend from "@/extension/mes/mes/ProductPickMaterial.jsx";
import viewOptions from './ProductPickMaterial/options.js'
import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
import productPickMaterialDetail from './ProductPickMaterialDetail.vue'
import selectProductTask from './ProductPickMaterialSelectProductTask.vue';
import selectMaterial from './ProductPickMaterialSelectMaterial.vue';
import selectProduct from './ProductPickMaterialSelectProduct.vue';

const grid = ref(null);
const materialRef = ref();
const productTaskRef = ref();
const productRef = ref();
const productPickMaterialDetailRef = ref();
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())

let gridRef;//对应[表.jsx]文件中this.使用方式一样
//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;
    //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
    //更多属性见：https://doc.volcore.xyz/docs/view-grid

    proxy.base.setItem('getPickMaterialSelectRow', () => {
        return gridRef.getTable(true).getSelected();
    })
    //设置弹出框编辑宽度
    // gridRef.boxOptions.width = 1100
    //启用明细表排序
    gridRef.detailOptions.sortable = true

    gridRef.detailOptions.pagination.sortName = "MaterialNo";  //明细表排序字字段
    gridRef.detailOptions.pagination.order = "asc"; //明细表排序方式desc或者asc

    const productTaskOption = gridRef.getFormOption("ProductTaskNo");
    productTaskOption.readonly = true;
    productTaskOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            productTaskRef.value.open();
        }
    };

    // 产品选择
    const productOption = gridRef.getFormOption("MaterialNo");
    productOption.readonly = true;
    productOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            productRef.value.open();
        }
    };
}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    columns.forEach(x => {
        //开启表头过滤
        x.filterData = true;
    })
    
    gridRef.height = gridRef.height - 310;
    if (gridRef.height < 200) {
        gridRef.height = 200;
    }

    gridRef.buttons.splice(3, 0, {
        name: '同步到云星辰', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            SyncData();
        }
    })
    gridRef.buttons.splice(4, 0, {
        name: '获取材料成本', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            SyncDataCost();
        }
    })
    //明细表行数据物料编码设置弹出框选择数据
    detail.columns.forEach((x) => {
        if (x.field == 'MaterialNo') {
            x.render = (h, { row, column, index }) => {
                x.edit = null;//设置当前字段不可编辑
                return (
                    <div>
                        <el-button link
                            onClick={($e) => {
                                $e.stopPropagation();
                                //触发事件
                                materialRef.value.open(row)
                            }}
                            class="el-icon-search"
                            style="color: #2196F3;cursor: pointer;"
                        ></el-button>
                        <span style="margin-left:5px">{row.MaterialNo}</span>
                    </div>
                );
            };
        }
    })

    gridRef.detailOptions.columns.forEach(c => {
        if (c.field == 'LotText') {
            c.checkEdit = (row, column, index) => {
                if (row.IsLoted == 1) {
                    c.required = true
                    return true
                }
                else {
                    c.required = false
                    return false
                }
            }
        }

    })

    gridRef.detailOptions.columns.forEach(x => {
        if (x.field == 'MaterialId') {
            //将eidt设置为null不开启编辑
            x.edit = null;
            initLotSelectTable()
        }
    })
    gridRef.detailOptions.columns.forEach(x => {
        if (x.field == 'StockId') {
            //如果字段是下拉框或日期，添加onChange事件
            x.onChange = (row, column, event) => {
                selectChange(row, column)
            }
        }
    })
}
//触发第二个下拉框联动操作
const selectChange = (row, column) => {
    //找到第二个下拉框选项
    let col = gridRef.detailOptions.columns.find((c) => { return c.field == 'LocationId' })
    let url = 'api/Location/getLocationByStockId'
    //从后台返回第二个下拉框满足条件的数据
    proxy.http.post(url, row.StockId, false).then((locationInfos) => {
        //keys只返回第二个下拉框的key值，用于下面的判断，返回的下拉框key选项显示，没有返回的隐藏
        console.log(locationInfos)
        col.bind.data.forEach((item) => {
            console.log(item)
            console.log(item.key)
            console.log(locationInfos[0] == item.key)

            //注意：第二个下拉框选项，在下拉框绑定页面，配置的字典sql需要将全部数据源返回
            //如果返回的数据源有几十W，请考虑用弹出框选择数据，不要用下拉框
            if (locationInfos.indexOf(item.key + '') != -1) {
                console.log(item.key)
                item.hidden = false
            } else {
                console.log(item.key)
                item.hidden = true
            }
        })
    })
}
const initLotSelectTable = () => {

    gridRef.detailOptions.columns.forEach((item) => {
        if (item.field == 'LotText') {
            item.edit = { type: "selectTable" }
            item.readonly = false;

            item.url = 'api/LotMasterDetail/search';

            //输入框只读操作，需要将columns的search字段设置为true，否则无法过滤数据
            //item.inputReadonly=true;
            //设置显示的字段
            item.columns = [
                { field: 'LotMasterDetailId', title: '批号明细标识', type: 'string', width: 120, hidden: true },
                { field: 'LotText', title: '批号', type: 'string', width: 100, search: true },
                { field: 'StockId', title: '仓库标识', type: 'string', width: 120, hidden: true },
                { field: 'StockName', title: '仓库', type: 'string', width: 100 },
                { field: 'LocationId', title: '仓位标识', type: 'string', width: 120, hidden: true },
                { field: 'LocationName', title: '仓位', type: 'string', width: 100 },
                { field: 'KdStockName', title: '金蝶仓库', type: 'string', width: 100 },
                { field: 'KdLocationName', title: '金蝶仓位', type: 'string', width: 100 },
                { field: 'InvQty', title: '库存数量', type: 'string', width: 100 },
            ];

            //选中table数据后，回写到表单
            //editRow:当前正在编辑的行
            //rows:选中的行
            item.onSelect = (editRow, rows) => {
                editRow.LotMasterDetailId = rows[0].LotMasterDetailId;
                editRow.LotText = rows[0].LotText;
                editRow.StockId = rows[0].StockId;
                editRow.LocationId = rows[0].LocationId;
            };

            //(输入框搜索)表格数据加载前处理
            //editRow:当前正在编辑的行
            //param:请求的参数
            item.loadBefore = (editRow, param, callback) => {

                param.value = editRow.MaterialId;
                callback(true);
            };

            //表格数据加载后处理
            //editRow:当前正在编辑的行
            //rows:后台返回的数据
            item.loadAfter = (editRow, rows, callback, result) => {
                callback(true);
            };

            /****下面的这些都是可以选配置，上面的是必填的******/
            //监听输入框变动与回车事件
            item.onKeyPress = (val, $event, row) => {
                console.log(val);
                if ($event.keyCode == 13) {
                    console.log('按了回车');
                }
                //清空值时给其他字段设置值
                // if(!val&&value+''!='0'){
                //     row.xx=null;
                // }
            }
            //设置弹出框高度(默认200)
            item.height = 200;
            //设置弹出框宽度(默认500)
            item.selectWidth = 800;
            item.textInline = true; //设置表格超出显示...
            //设置表格是否单选
            item.single = true;
            //隐藏分页
            item.paginationHide = true;
            //设置默认分页大小与分页信息
            item.pagination = { size: 30, sizes: [30, 60, 90] };
        }
    });
}
//表格回写事件
const onSelectMaterial = (row) => {
    console.log('表格回写事件')
}

//选择生产任务回调
const onSelectProductTask = (rows) => {
    editFormFields.ProductTaskId = rows[0].ProductTaskId;
    editFormFields.ProductTaskNo = rows[0].BillNo;
    editFormFields.ProductPlanNo = rows[0].ProductPlanNo;
    editFormFields.DepartmentId = rows[0].DepartmentId;
    editFormFields.Remark = rows[0].Remark;
    //这里还可以给其他字段设置值editFormFields.字段=
}

// 选择产品回调
const onSelectProduct = (rows) => {
    editFormFields.MaterialId = rows[0].MaterialId;
    editFormFields.MaterialNo = rows[0].Code;
    editFormFields.MaterialName = rows[0].Name;
    editFormFields.Spec = rows[0].Spec;
    editFormFields.MaterialTypeId = rows[0].MaterialTypeId;
}

const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询
    return true;
}
const searchAfter = async (rows, result) => {
    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const delBefore = (ids, rows) => { //查询界面的表删除前 ids为删除的id数组,rows删除的行
    let isDeleted = true
    rows.forEach(row => {
        if (row.AuditStatus != 0 && row.AuditStatus != null) {
            isDeleted = false
            proxy.$message.error(row.BillNo + "已审核不允许删除！");
            return isDeleted;
        }
    });
    return isDeleted;//返回false，界面上不会显示
}
const rowClick = ({ row, column, event }) => {
    //点击行清除选中的行(用于下面明细表判断)
    grid.value.clearSelection();
    //查询界面点击行事件
    grid.value.toggleRowSelection(row); //单击行时选中当前行;
    //加载明细表
    productPickMaterialDetailRef.value.$refs.grid.search();
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
    gridRef.setFormReadonly(false);

    if (gridRef.currentAction == 'Add') {

        gridRef.detailOptions.columns.forEach((item) => {
            if (item.field == "MaterialName"
                || item.field == "Spec"
                || item.field == "MaterialTypeId"
                || item.field == "UnitId"
                || item.field == "IsLoted"
                || item.field == "IsCriticalParts"

            ) {
                item.readonly = true
            }
        })

        gridRef.editFormFields.BillTypeId = 2
        gridRef.editFormFields.BillDate = proxy.base.getDate()
        gridRef.boxButtons.forEach((btn) => {
            if (btn.name == '保存') {
                btn.hidden = false;
                //或者设置只读
                // btn.readonly = true;
            }
        });
    }
    else {
        if (row.AuditStatus != 0 && row.AuditStatus != null) {
            gridRef.setFormReadonly(true);
            gridRef.boxButtons.forEach((btn) => {
                if (btn.name == '保存') {
                    btn.hidden = true;
                    //或者设置只读
                    // btn.readonly = true;
                }
            });
        }
        else {
            gridRef.detailOptions.columns.forEach((item) => {
                if (item.field == "MaterialName"
                    || item.field == "Spec"
                    || item.field == "MaterialTypeId"
                    || item.field == "UnitId"
                    || item.field == "IsLoted"

                ) {
                    item.readonly = true
                }
            })
            gridRef.boxButtons.forEach((btn) => {
                if (btn.name == '保存') {
                    btn.hidden = false;
                    //或者设置只读
                    // btn.readonly = true;
                }
            });
        }
    }
}
const SyncData = () => {
    var rows = gridRef.getSelectRows()
    if (rows.length == 0) {
        proxy.$message.error("请选择领料单");
        return
    }
    if (rows[0].AuditStatus != 1) {
        proxy.$message.error("领料单未审核");
        return
    }
    let url = 'api/ProductPickMaterial/syncData';
    proxy.http.post(url, rows).then((result) => {

        proxy.$message.success("同步数据成功！");
    });
}
const SyncDataCost = () => {
    var rows = gridRef.getSelectRows()
    if (rows.length == 0) {
        proxy.$message.error("请选择领料单");
        return
    }
    let url = 'api/ProductPickMaterial/syncDataCost';
    proxy.http.post(url, rows).then((result) => {

        proxy.$message.success("同步数据成功！");
    });
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
